

// 根据json树 和某一节点id 查找该节点所有祖先级节点
export const getTreeIds = (tree, nodeId, config) => {
  const { children = "children", id = "id" } = config || {};
  //扁平化json树
  const toFlatArray = (tree, parentId) => {
    return tree.reduce((t, _) => {
      const child = _[children];
      return [
        ...t,
        parentId
          ? {
              ..._,
              parentId,
            }
          : _,
        ...(child && child.length ? toFlatArray(child, _[id]) : []),
      ];
    }, []);
  };
  // 根据json树和节点id,查找节点的所有父节点
  const getIds = (flatArray) => {
    let ids = [nodeId];
    let nodeArr = [];
    let child = flatArray.find((_) => _[id] == nodeId);
    nodeArr.unshift(child);
    while (child && child.parentId) {
      ids = [child.parentId, ...ids];
      child = flatArray.find((_) => _[id] == child.parentId);
      nodeArr.unshift(child);
    }
    return {
      ids,
      nodeArr,
    };
  };
  return getIds(toFlatArray(tree));
};

// 数组扁平化
export function flatten(arr) {
  return arr.reduce((a, b) => a.concat(Array.isArray(b) ? flatten(b) : b), []);
}
// 数组去重
export function unique(arr) {
  let result = [];
  for (let i = 0; i < arr.length; i++) {
    if (result.indexOf(arr[i]) == -1) {
      result.push(arr[i]);
    }
  }
  return result;
}

/**
 * 根据传入的条件 返回json数据中符合条件的数据
 * params: treeList  需要处理的原始数据
 * params: callback 条件function 如:(node)=>node.id==id
 *  */
export function filter(treeList, callback) {
  const queue = [...treeList];
  while (queue.length > 0) {
    const cur = queue.shift();
    if (callback(cur)) {
      return cur;
    }
    if (cur.children?.length > 0) {
      for (const item of cur.children) {
        queue.push(item);
      }
    }
  }
}
